package cn.stylefeng.mferp.modular.dispatch.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.stylefeng.mferp.core.common.constant.DatasourceEnum;
import cn.stylefeng.mferp.core.util.DateUtil;
import cn.stylefeng.mferp.core.util.HtmlDecodeUtil;
import cn.stylefeng.mferp.core.util.ReflectUtil;
import cn.stylefeng.mferp.modular.business.model.TrwdSaveModel;
import cn.stylefeng.mferp.modular.business.warpper.TrwdWarpper;
import cn.stylefeng.mferp.modular.dispatch.constant.Constants;
import cn.stylefeng.mferp.modular.dispatch.dao.TRwdMapper;
import cn.stylefeng.mferp.modular.dispatch.model.TRwd;
import cn.stylefeng.mferp.modular.dispatch.model.TRwdSaveModel;
import cn.stylefeng.mferp.modular.dispatch.model.TRwdTodayReportModel;
import cn.stylefeng.mferp.modular.dispatch.service.ITRwdService;
import cn.stylefeng.mferp.modular.dispatch.wrapper.TRwdWarpper;
import cn.stylefeng.roses.core.mutidatasource.annotion.DataSource;
import cn.stylefeng.roses.core.reqres.response.ErrorResponseData;
import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TRwdServiceImpl extends ServiceImpl<TRwdMapper, TRwd> implements ITRwdService {

    @Autowired
    private TRwdMapper tRwdMapper;

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_DISPATCH)
    public Object selectTrwds(String beginTime, String endTime, String gcmc, String rwdh, String scbt, String zt) {
        //List<Map<String, Object>> trwds = tRwdMapper.selectTrwds(beginTime, endTime, gcmc, rwdh, scbt, zt);
        Wrapper<TRwd> wrapper = new EntityWrapper<>();
        if (StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)) {
            wrapper.ge("left(Fjhrq, 10)", beginTime);
            wrapper.le("left(Fjhrq, 10)", endTime);
        }
        wrapper.like(StringUtils.isNotBlank(gcmc), "Fgcmc", gcmc);
        wrapper.like(StringUtils.isNotBlank(rwdh), "Frwdh", rwdh);
        wrapper.eq(StringUtils.isNotBlank(scbt), "Fscbt", scbt);
        wrapper.eq(StringUtils.isNotBlank(zt), "Fzt", zt);
        List<TRwd> list = this.selectList(wrapper);
        if (list == null || list.isEmpty()) {
            return new TRwdWarpper(Collections.emptyList()).wrap();
        }
        List<Map<String, Object>> multi = list.stream().map(tRwd -> {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(tRwd));
            return jsonObject.getInnerMap();
        }).collect(Collectors.toList());
        return new TRwdWarpper(multi).wrap();
    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_DISPATCH)
    public TRwd selectByRwdh(String rwdh) {
        Wrapper<TRwd> wrapper = new EntityWrapper<>();
        wrapper.eq("Frwdh", rwdh);
        return this.selectOne(wrapper);
    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_DISPATCH)
    public Object getTrwdByFrwdh(String rwdh) {
        if (StringUtils.isBlank(rwdh)) {
            return new ErrorResponseData("任务单号不能为空");
        }
        log.info("getTrwdByFrwdh 任务单号:{}", rwdh);
        Wrapper<TRwd> wrapper = new EntityWrapper<>();
        wrapper.eq("Frwdh", rwdh);
        TRwd tRwd = this.selectOne(wrapper);
        if (tRwd == null) {
            return new ErrorResponseData("该单号的任务单不存在");
        }
        tRwd.setZlyq(tRwd.getFssyq());
        String ftbj = tRwd.getFtbj();
        if (StringUtils.isNotBlank(ftbj) && ftbj.contains("|")) {
            String[] split = ftbj.split("\\|");
            tRwd.setGddh(split[0]);
        }
        return new SuccessResponseData(tRwd);
    }

    /**
     * 更小单号任务单
     * @param rwdh
     * @return
     */
    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_DISPATCH)
    public Object getLastTrwdByFrwdh(String rwdh) {
        if (StringUtils.isBlank(rwdh)) {
            return new ErrorResponseData("任务单号不能为空");
        }
        log.info("getLastTrwdByFrwdh 任务单号:{}", rwdh);
        Wrapper<TRwd> wrapper = new EntityWrapper<>();
        if (Objects.equals(rwdh, "0")) {
            wrapper.orderBy("Frwdh", false);
            wrapper.setSqlSelect(" top 1 * ");
        } else {
            wrapper.orderBy("Frwdh", false);
            wrapper.lt("Frwdh", rwdh);
            wrapper.setSqlSelect(" top 1 * ");
        }
        TRwd tRwd = this.selectOne(wrapper);
        if (tRwd == null) {
            return new ErrorResponseData("该单号不存在更小单号的任务单");
        }
        tRwd.setZlyq(tRwd.getFssyq());
        String ftbj = tRwd.getFtbj();
        if (StringUtils.isNotBlank(ftbj) && ftbj.contains("|")) {
            String[] split = ftbj.split("\\|");
            tRwd.setGddh(split[0]);
        }
        return new SuccessResponseData(tRwd);
    }

    /**
     * 更大单号任务单
     * @param rwdh
     * @return
     */
    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_DISPATCH)
    public Object getNextTrwdByFrwdh(String rwdh) {
        if (StringUtils.isBlank(rwdh)) {
            return new ErrorResponseData("任务单号不能为空");
        }
        log.info("getNextTrwdByFrwdh 任务单号:{}", rwdh);
        Wrapper<TRwd> wrapper = new EntityWrapper<>();
        if (Objects.equals(rwdh, "0")) {
            wrapper.orderBy("Frwdh", true);
            wrapper.setSqlSelect(" top 1 * ");
        } else {
            wrapper.orderBy("Frwdh", true);
            wrapper.gt("Frwdh", rwdh);
            wrapper.setSqlSelect(" top 1 * ");
        }
        TRwd tRwd = this.selectOne(wrapper);
        if (tRwd == null) {
            return new ErrorResponseData("该单号不存在更大单号的任务单");
        }
        tRwd.setZlyq(tRwd.getFssyq());
        String ftbj = tRwd.getFtbj();
        if (StringUtils.isNotBlank(ftbj) && ftbj.contains("|")) {
            String[] split = ftbj.split("\\|");
            tRwd.setGddh(split[0]);
        }
        return new SuccessResponseData(tRwd);
    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_DISPATCH)
    public Object getTrwdList(String gcmc, String rwdh) {
        if (StringUtils.isBlank(gcmc) && StringUtils.isBlank(rwdh)) {
            return new TRwdWarpper(Collections.emptyList()).wrap();
        }
        Wrapper<TRwd> wrapper = new EntityWrapper<>();
        wrapper.like(StringUtils.isNotBlank(gcmc), "Fgcmc", gcmc);
        wrapper.like(StringUtils.isNotBlank(rwdh), "Frwdh", rwdh);
        wrapper.orderBy("Frwdh", false);
        List<TRwd> list = this.selectList(wrapper);
        if (list == null || list.isEmpty()) {
            return new TRwdWarpper(Collections.emptyList()).wrap();
        }
        List<Map<String, Object>> multi = list.stream().map(tRwd -> {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(tRwd));
            return jsonObject.getInnerMap();
        }).collect(Collectors.toList());
        return new TRwdWarpper(multi).wrap();
    }

    /**
     * 查找今天下单的任务单
     * @return
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_DISPATCH)
    @Override
    public Object getTrwdListToday() {
        String currDate = DateUtil.getCurrentDate();
        Wrapper<TRwd> wrapper = new EntityWrapper<>();
        wrapper.eq("Fdlrq", currDate);
        wrapper.orderBy("Frwdh", false);
        List<TRwd> list = this.selectList(wrapper);
        if (list == null || list.isEmpty()) {
            return new TRwdWarpper(Collections.emptyList()).wrap();
        }
        List<Map<String, Object>> multi = list.stream().map(tRwd -> {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(tRwd));
            return jsonObject.getInnerMap();
        }).collect(Collectors.toList());
        return new TRwdWarpper(multi).wrap();
    }

    @DataSource(name = DatasourceEnum.DATA_SOURCE_DISPATCH)
    @Override
    public Object saveTRwd(TRwdSaveModel data) {
        if (data == null) {
            return new ErrorResponseData("参数不能为空");
        }
        log.info("saveTrwd data:{}", JSON.toJSONString(data));

        if (StringUtils.isBlank(data.getFgcmc())) {
            return new ErrorResponseData("工程名称不能为空");
        }
        if (StringUtils.isBlank(data.getFjzbw())) {
            return new ErrorResponseData("浇筑部位不能为空");
        }
        if (StringUtils.isBlank(data.getFhtdw())) {
            return new ErrorResponseData("施工单位不能为空");
        }
        if (StringUtils.isBlank(data.getFgcmc())) {
            return new ErrorResponseData("工程名称不能为空");
        }
        if (data.getFjhsl() == null) {
            return new ErrorResponseData("预计方量不能为空");
        }
        if (StringUtils.isBlank(data.getFjhrq())) {
            return new ErrorResponseData("浇筑时间不能为空");
        }

        TRwd trwd = new TRwd();
        trwd.setFgcmc(HtmlDecodeUtil.unescapeHtml(data.getFgcmc()));
        trwd.setFhtdw(data.getFhtdw());
        trwd.setFjzbw(data.getFjzbw());
        trwd.setFtpz(data.getFtpz());
        trwd.setFjhsl(data.getFjhsl());
        trwd.setFjhrq(data.getFjhrq());
        trwd.setFjzfs(data.getFjzfs());
        trwd.setFgcdz(data.getFgcdz());
        trwd.setFtld(data.getFtld());
        trwd.setFrwxz(data.getFrwxz());

        trwd.setFzt("新任务单");
        trwd.setFgls(BigDecimal.ZERO.doubleValue());
        trwd.setFszgg("/");
        trwd.setFscbt("*");
        trwd.setFwcsl(BigDecimal.ZERO.doubleValue());
        trwd.setFczy("接单员");
        trwd.setFsgpb(0);
        trwd.setFljcs(0);
        trwd.setFdlrq(DateUtil.getCurrentDate());
        trwd.setFxpkey(ThreadLocalRandom.current().nextLong(499999999999999999L, 999999999999999999L));
        if (StringUtils.isBlank(data.getZlyq())) {
            data.setZlyq("");
        }
        if (StringUtils.isBlank(data.getGddh())) {
            data.setGddh("");
        }
        // 要过磅（0-5石子)15160003829|/|||||15160003829|||||
        // 备注|渗料规格|外加剂规格|抗渗等级|其他要求|施工单位联系人|工程编号|营销部门联系人|监督号码|优先采用的仓库编号|监控系统工地号|质检员
        // 备注和联系电话
        trwd.setFtbj(data.getGddh() + "|/|||||" + data.getGddh() + "|||||");
        trwd.setFssyq(data.getZlyq());

        Integer insert = tRwdMapper.insert(trwd);
        if (insert > 0) {
            trwd.setFrwno(String.valueOf(trwd.getFrwdh()));
            tRwdMapper.updateById(trwd);
        }
        return new SuccessResponseData(trwd);
    }

    @Override
    public Object analyseContent(String content) {
        log.info("sbContent content:{}", content);
        if (StringUtils.isBlank(content)) {
            return new ErrorResponseData("参数不能为空");
        }
        // 去除转义字符
        content = HtmlDecodeUtil.unescapeHtml(content);
        //content = content.replace("& lt;p& gt;", "");
        //content = content.replace("& lt;/p& gt;", "");
        //content = content.replace("&nbsp;", "");
        content = content.replace("：", ":");
        content = content.replace(": ", ":");
        content = content.replace("\t", "");
        String[] array = content.split("\n");
        log.info(String.valueOf(array.length));
        String[] list = array;
        TrwdSaveModel trwd = new TrwdSaveModel();
        for (String a : list) {
            log.info(a);
            if (!a.contains(":") || StringUtils.isBlank(a)) {
                continue;
            }
            int i = a.indexOf(":");
            if (i == -1) {
                continue;
            }
            String name = a.substring(0, i);
            String value = a.substring(i + 1);
            if (StringUtils.isBlank(name) || StringUtils.isBlank(value)) {
                continue;
            }
            name = name.trim();
            value = value.trim();
            log.info(value);
            if (parseJhrq(name, value, trwd) || parseJzbw(name, value, trwd) || parseFtpz(name, value, trwd) ||
                    parseFjhsl(name, value, trwd) || parseFjzfs(name, value, trwd) || parseGddh(name, value, trwd) ||
                    parseGcdz(name, value, trwd) || parseZlyq(name, value, trwd) || parseFtld(name, value, trwd)) {
                continue;
            }
            if (name.contains("工程名称")) {
                trwd.setFgcmc(value);
            } else if (name.contains("施工单位")) {
                trwd.setFhtdw(value);
            }
        }
        String fjzfs = trwd.getFjzfs();
        if (StringUtils.isBlank(trwd.getFtld()) && StringUtils.isNotBlank(trwd.getFjzfs())) {
            boolean fb = Arrays.stream(Constants.TLD_STR_ARRAY1).anyMatch(fjzfs::contains);
            boolean bs = Arrays.stream(Constants.TLD_STR_ARRAY2).anyMatch(fjzfs::contains);
            if (fb) {
                trwd.setFtld("100±20");
            } else if (bs) {
                trwd.setFtld("150±30");
            } else {
                trwd.setFtld("/");
            }
        }
        String tpz = trwd.getFtpz();
        if (StringUtils.isNotBlank(tpz)) {
            boolean b = Arrays.stream(Constants.TLD_STR_ARRAY3).anyMatch(tpz::contains);
            if (b) {
                trwd.setFtld("/");
            } else if (tpz.contains("细石")) {
                trwd.setFtld("100±20");
            } else if (tpz.contains("水下")) {
                trwd.setFtld("200±20");
            }
        }

        if (StringUtils.isBlank(trwd.getZlyq())) {
            trwd.setZlyq(Constants.DEFAULT_NULL_VALUE);
        }

        String fgcdz = trwd.getFgcdz();
        if (StringUtils.isBlank(fgcdz)) {
            trwd.setFgcdz(Constants.DEFAULT_NULL_VALUE);
        }

        String fjhrq = trwd.getFjhrq();
        if (StringUtils.isBlank(fjhrq)) {
            trwd.setFjhrq(DateUtil.getDateFormat(DateUtil.addDayByDate(new Date(), 1), "yyyy-MM-dd"));
        }

        return new SuccessResponseData(trwd);
    }

    @DataSource(name = DatasourceEnum.DATA_SOURCE_DISPATCH)
    @Override
    public Object updateTRwd(TRwdSaveModel data) {
        if (data == null) {
            return new ErrorResponseData("参数不能为空");
        }
        log.info("saveTrwd data:{}", JSON.toJSONString(data));
        Integer frwdh = data.getFrwdh();
        if (frwdh == null) {
            return new ErrorResponseData("任务单号不能为空");
        }
        TRwd trwd = tRwdMapper.selectById(frwdh);
        if (trwd == null) {
            return new ErrorResponseData("当前任务单不存在，修改失败");
        }
        if (!Objects.equals(trwd.getFzt(), "新任务单")) {
            return new ErrorResponseData("当前任务单不是新任务单，不允许修改");
        }

        if (StringUtils.isBlank(data.getFgcmc())) {
            return new ErrorResponseData("工程名称不能为空");
        }
        if (StringUtils.isBlank(data.getFjzbw())) {
            return new ErrorResponseData("浇筑部位不能为空");
        }
        if (StringUtils.isBlank(data.getFhtdw())) {
            return new ErrorResponseData("施工单位不能为空");
        }
        if (StringUtils.isBlank(data.getFgcmc())) {
            return new ErrorResponseData("工程名称不能为空");
        }
        if (data.getFjhsl() == null) {
            return new ErrorResponseData("预计方量不能为空");
        }
        if (StringUtils.isBlank(data.getFjhrq())) {
            return new ErrorResponseData("浇筑时间不能为空");
        }

        trwd.setFgcmc(HtmlDecodeUtil.unescapeHtml(data.getFgcmc()));
        trwd.setFhtdw(data.getFhtdw());
        trwd.setFjzbw(data.getFjzbw());
        trwd.setFtpz(data.getFtpz());
        trwd.setFjhsl(data.getFjhsl());
        trwd.setFjhrq(data.getFjhrq());
        trwd.setFjzfs(data.getFjzfs());
        trwd.setFgcdz(data.getFgcdz());
        trwd.setFtld(data.getFtld());
        trwd.setFrwxz(data.getFrwxz());

        trwd.setFgls(BigDecimal.ZERO.doubleValue());
        trwd.setFszgg("/");
        trwd.setFscbt("*");
        trwd.setFwcsl(BigDecimal.ZERO.doubleValue());
        trwd.setFczy("接单员");
        trwd.setFsgpb(0);
        trwd.setFljcs(0);
        trwd.setFdlrq(DateUtil.getCurrentDate());
        trwd.setFxpkey(ThreadLocalRandom.current().nextLong(499999999999999999L, 999999999999999999L));
        if (StringUtils.isBlank(data.getZlyq())) {
            data.setZlyq("");
        }
        if (StringUtils.isBlank(data.getGddh())) {
            data.setGddh("");
        }
        // 要过磅（0-5石子)15160003829|/|||||15160003829|||||
        // 备注|渗料规格|外加剂规格|抗渗等级|其他要求|施工单位联系人|工程编号|营销部门联系人|监督号码|优先采用的仓库编号|监控系统工地号|质检员
        // 备注和联系电话
        trwd.setFtbj(data.getGddh() + "|/|||||" + data.getGddh() + "|||||");
        trwd.setFssyq(data.getZlyq());
        trwd.setFversion(null);

        tRwdMapper.updateById(trwd);
        return new SuccessResponseData(trwd);
    }

    /**
     * 解析计划日期
     * @param name 字段名
     * @param value 字段值
     * @param trwd 任务单
     */
    private boolean parseJhrq(String name, String value, TrwdSaveModel trwd) {
        boolean b = Arrays.stream(Constants.JHRQ_STR_ARRAY).anyMatch(name::contains);
        if (StringUtils.isNotBlank(name) && b && StringUtils.isBlank(trwd.getFjhrq())) {
            try {
                String s = parseJhrq(value);
                if (StringUtils.isNotBlank(s)) {
                    s = DateUtil.parseDateTimeStr(s);
                }
                trwd.setFjhrq(s);
            } catch (Exception e) {
                trwd.setFjhrq("");
            }
            return true;
        }
        return false;
    }

    private String parseJhrq(String value) {
        String temp = value;
        StringBuilder jhrq = new StringBuilder();
        if (temp.contains("-") && temp.contains(":")) {
            jhrq.append(parseJhrq1(temp));
        } else if (temp.contains("/") && temp.contains(":")) {
            jhrq.append(parseJhrq2(temp));
        } else if (temp.contains("-")) {
            temp = parseJhrq3(temp);
            jhrq.append(temp.replace("/", "-"));
        } else if (temp.contains("/")) {
            temp = parseJhrq3(temp);
            jhrq.append(temp.replace("/", "-"));
        } else {
            jhrq.append(parseJhrq5(temp));
        }
        log.info(jhrq.toString());
        return jhrq.toString();
    }
    private String parseJhrq1(String temp) {
        StringBuilder jhrq = new StringBuilder();
        temp = temp.replace(Constants.YEAR_STR, "-");
        temp = temp.replace(Constants.MONTH_STR, "-");
        temp = temp.replace(Constants.DAY_STR, " ");
        String s = temp.split(" ")[1];
        if (StringUtils.isBlank(s)) {
            temp = temp.split(" ")[0];
            return temp.replace("/", "-");
        }
        return jhrq.append(temp.replace("/", "-")).toString();
    }
    private String parseJhrq2(String temp) {
        StringBuilder jhrq = new StringBuilder();
        temp = temp.replace(Constants.YEAR_STR, "-");
        temp = temp.replace(Constants.MONTH_STR, "-");
        temp = temp.replace(Constants.DAY_STR, "");
        String s = temp.split(" ")[1];
        if (StringUtils.isBlank(s)) {
            temp = temp.split(" ")[0];
            return temp.replace("/", "-");
        }
        return jhrq.append(temp.replace("/", "-")).toString();
    }
    private String parseJhrq3(String temp) {
        String sperator = temp.contains("/") ? "/" : "-";
        StringBuilder jhrq = new StringBuilder();
        String date = temp.split(" ")[0];
        date = date.replace(Constants.YEAR_STR, sperator);
        date = date.replace("--", sperator);
        date = date.replace("//", sperator);
        date = date.replace(Constants.MONTH_STR, sperator);
        date = date.replace("--", sperator);
        date = date.replace("//", sperator);
        date = date.replace(Constants.DAY_STR, "");
        jhrq.append(date);
        try {
            temp = temp.split(" ")[1];
        } catch (Exception e) {
            temp = "";
        }
        if (StringUtils.isNotBlank(temp)) {
            boolean isAm = true;
            for (String pmStr : Constants.PM_STR_ARRAY) {
                if (temp.contains(pmStr)) {
                    temp = temp.replace(pmStr, "");
                    isAm = false;
                    break;
                }
            }
            for (String amStr : Constants.AM_STR_ARRAY) {
                if (temp.contains(amStr)) {
                    temp = temp.replace(amStr, "");
                    isAm = true;
                    break;
                }
            }
            for (String timeStr : Constants.TIME_STR_ARRAY) {
                temp = temp.replace(timeStr, Constants.HOUR_STR);
            }
            String hour = temp.split(Constants.HOUR_STR)[0].trim();
            if (!isAm && Integer.parseInt(hour) < 12) {
                hour = String.valueOf(Integer.parseInt(hour) + 12);
            }
            jhrq.append(" ").append(hour).append(":00:00");
        } else {
            jhrq.append(temp).append(" 00:00:00");
        }
        return jhrq.toString();
    }
    private String parseJhrq5(String temp) {
        StringBuilder jhrq = new StringBuilder();
        temp = temp.replace(":00", "点");
        log.info(temp);
        if (temp.contains(Constants.YEAR_STR)) {
            String year = temp.split(Constants.YEAR_STR)[0].trim();
            jhrq.append(year).append("-");
            temp = temp.split(Constants.YEAR_STR)[1].trim();
        } else {
            String year = LocalDateTime.now().getYear() + "";
            jhrq.append(year).append("-");
        }
        if (temp.contains(Constants.MONTH_STR)) {
            String month = temp.split(Constants.MONTH_STR)[0].trim();
            jhrq.append(month).append("-");
            temp = temp.split(Constants.MONTH_STR)[1].trim();
        } else {
            String month = LocalDateTime.now().getMonthValue() + "";
            jhrq.append(month).append("-");
        }
        if (temp.contains(Constants.DAY_STR)) {
            String day = temp.split(Constants.DAY_STR)[0].trim();
            jhrq.append(day);
            if (temp.split(Constants.DAY_STR).length == 2) {
                temp = temp.split(Constants.DAY_STR)[1].trim();
            } else {
                temp = "";
            }
        } else {
            String day = LocalDateTime.now().getDayOfMonth() + "";
            jhrq.append(day).append(" ");
            temp = temp.split(" ")[1];
        }
        if (StringUtils.isNotBlank(temp)) {
            boolean isAm = true;
            for (String pmStr : Constants.PM_STR_ARRAY) {
                if (temp.contains(pmStr)) {
                    temp = temp.replace(pmStr, "");
                    isAm = false;
                    break;
                }
            }
            for (String amStr : Constants.AM_STR_ARRAY) {
                if (temp.contains(amStr)) {
                    temp = temp.replace(amStr, "");
                    isAm = true;
                    break;
                }
            }
            for (String timeStr : Constants.TIME_STR_ARRAY) {
                temp = temp.replace(timeStr, Constants.HOUR_STR);
            }
            String hour = temp.split(Constants.HOUR_STR)[0].trim();
            if (!isAm && Integer.parseInt(hour) < 12) {
                hour = String.valueOf(Integer.parseInt(hour) + 12);
            }
            jhrq.append(" ").append(hour).append(":00:00");
        } else {
            jhrq.append(" ").append(temp).append("00:00:00");
        }
        return jhrq.toString();
    }
    /**
     * 解析浇筑部位
     */
    private boolean parseJzbw(String name, String value, TrwdSaveModel trwd) {
        boolean b = Arrays.stream(Constants.JZBW_STR_ARRAY).anyMatch(name::contains);
        if (b && StringUtils.isBlank(trwd.getFjzbw())) {
            trwd.setFjzbw(value.trim());
            return true;
        }
        return false;
    }
    /**
     * 解析强度等级
     */
    private boolean parseFtpz(String name, String value, TrwdSaveModel trwd) {
        boolean b = Arrays.stream(Constants.TPZ_STR_ARRAY).anyMatch(name::contains);
        if (b && StringUtils.isBlank(trwd.getFtpz())) {
            trwd.setFtpz(value.trim());
            return true;
        }
        return false;
    }
    /**
     * 解析计划方量
     */
    private boolean parseFjhsl(String name, String value, TrwdSaveModel trwd) {
        boolean b = Arrays.stream(Constants.JHSL_STR_ARRAY).anyMatch(name::contains);
        final String[] temp = {value};
        if (b && trwd.getFjhsl() == null) {
            Arrays.stream(Constants.JHSL_UNIT_STR_ARRAY).forEach(unit -> temp[0] = temp[0].replace(unit, ""));
            String jhsl = temp[0];
            jhsl = jhsl.replace("\r", "").replace("\n", "").replace("\t", "").replace(" ", "");
            log.info(jhsl);
            if (NumberUtil.isNumber(jhsl)) {
                trwd.setFjhsl(new BigDecimal(jhsl).doubleValue());
            } else {
                trwd.setFjhsl(BigDecimal.ZERO.doubleValue());
            }
            return true;
        }
        return false;
    }
    /**
     * 解析浇筑方式
     */
    private boolean parseFjzfs(String name, String value, TrwdSaveModel trwd) {
        boolean b = Arrays.stream(Constants.JZFS_STR_ARRAY).anyMatch(name::contains);
        if (b && StringUtils.isBlank(trwd.getFjzfs())) {
            trwd.setFjzfs(value);
            return true;
        }
        return false;
    }
    /**
     * 解析工地电话
     */
    private boolean parseGddh(String name, String value, TrwdSaveModel trwd) {
        boolean b = Arrays.stream(Constants.GDDH_STR_ARRAY).anyMatch(name::contains);
        if (b && StringUtils.isBlank(trwd.getGddh())) {
            trwd.setGddh(value.replace(" ", "").trim());
            return true;
        }
        return false;
    }
    /**
     * 解析工程地址
     */
    private boolean parseGcdz(String name, String value, TrwdSaveModel trwd) {
        boolean b = Arrays.stream(Constants.GCDZ_STR_ARRAY).anyMatch(name::contains);
        if (b && StringUtils.isBlank(trwd.getFgcdz())) {
            trwd.setFgcdz(value.trim());
            return true;
        }
        return false;
    }
    /**
     * 解析资料要求
     */
    private boolean parseZlyq(String name, String value, TrwdSaveModel trwd) {
        boolean b = Arrays.stream(Constants.ZLYQ_STR_ARRAY).anyMatch(name::contains);
        if (b && StringUtils.isBlank(trwd.getZlyq())) {
            trwd.setZlyq(value.trim());
            return true;
        } else if (b && StringUtils.isNotBlank(trwd.getZlyq())) {
            trwd.setZlyq(trwd.getZlyq()+ " " + value.trim());
            return true;
        } else if (name.contains(Constants.ZLYQ_STR_KPJD) && value.contains("要") && !value.contains("不")) {
            trwd.setZlyq(StringUtils.isNotBlank(trwd.getZlyq()) ? trwd.getZlyq() + " " + Constants.ZLYQ_STR_KPJD : Constants.ZLYQ_STR_KPJD);
            return true;
        } else if (name.contains(Constants.ZLYQ_STR_SJ) && value.contains("是") && !value.contains("不")) {
            trwd.setZlyq(StringUtils.isNotBlank(trwd.getZlyq()) ? trwd.getZlyq() + " " + Constants.ZLYQ_STR_SK : Constants.ZLYQ_STR_SK);
            return true;
        }
        return false;
    }
    /**
     * 解析塌落度
     */
    private boolean parseFtld(String name, String value, TrwdSaveModel trwd) {
        boolean b = Arrays.stream(Constants.TLD_STR_ARRAY).anyMatch(name::contains);
        if (b && StringUtils.isBlank(trwd.getFtld())) {
            trwd.setFtld(value.trim());
            return true;
        }
        return false;
    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_DISPATCH)
    public void downloadTodayReport(HttpServletResponse response, String beginTime, String endTime, String excelType) throws IOException {
        log.info("downloadTodayReport：{} {}", beginTime, endTime);
        String currDate = DateUtil.getCurrDate("yyyy年M月份");
        if (StringUtils.isBlank(beginTime)) {
            beginTime = DateUtil.getCurrentDate();
        }
        if (StringUtils.isBlank(endTime)) {
            endTime = DateUtil.getCurrentDate();
        }
        List<TRwd> trwds = tRwdMapper.selectTrwdList(beginTime, endTime);
        log.info("downloadTodayReport list:{}", trwds.size());
        List<TRwdTodayReportModel> trwdModels = new ArrayList<>();
        for (TRwd tRwd: trwds) {
            TRwdTodayReportModel trwdModel = new TRwdTodayReportModel();
            ReflectUtil.copyValue(tRwd, trwdModel);
            try {
                String fjhrq = tRwd.getFjhrq();
                if (fjhrq.contains("：")) {
                    fjhrq = fjhrq.replace("：", ":");
                    tRwd.setFjhrq(fjhrq);
                    tRwdMapper.updateById(tRwd);
                }
                if (StringUtils.isNotBlank(fjhrq)) {
                    String[] split = fjhrq.split(" ");
                    String date = split[0];
                    String time = split.length == 2 ? split[1] : "00:00:00";
                    String[] split1 = time.split(":");
                    if (split1.length == 1) {
                        time = split1[0] + ":00:00";
                    } else if (split1.length == 2) {
                        time = split1[0] + ":" + split1[1] + ":00";
                    }
                    trwdModel.setRq(DateUtil.getDateFormat(date, DateUtil.DATE_PATTERN1, "M月d日"));
                    trwdModel.setSj(DateUtil.getDateFormat(time, DateUtil.TIME_PATTERN1, "HH:mm"));
                }
            } catch (ParseException e) {
                trwdModel.setRq("");
                trwdModel.setSj("");
            }

            String ftbj = tRwd.getFtbj();
            if (StringUtils.isNotBlank(ftbj) && ftbj.contains("|")) {
                String[] split = ftbj.split("\\|");
                if (split.length > 0) {
                    tRwd.setGddh(split[0]);
                }
            }
            trwdModel.setZlyq(tRwd.getFssyq());
            trwdModels.add(trwdModel);
        }
        String thisFileName;
        ExcelWriter excelWriter;
        if(StringUtils.isNotBlank(excelType) && "03".equals(excelType)) {
            thisFileName = currDate + "日报表" + System.currentTimeMillis() + ExcelTypeEnum.XLS.getValue();
            excelWriter = EasyExcel.write(response.getOutputStream()).excelType(ExcelTypeEnum.XLS).build();
        } else {
            thisFileName = currDate + "日报表" + System.currentTimeMillis() + ExcelTypeEnum.XLSX.getValue();
            excelWriter = EasyExcel.write(response.getOutputStream()).excelType(ExcelTypeEnum.XLSX).build();
        }
        if(StringUtils.isNotBlank(thisFileName) && excelWriter != null && !trwdModels.isEmpty()) {
            try {
                // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
                response.setContentType("application/vnd.ms-excel");
                response.setCharacterEncoding("utf-8");
                // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
                String fileName = URLEncoder.encode(thisFileName, "UTF-8");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName);
                WriteSheet writeSheet1 = EasyExcel.writerSheet(0, currDate + "日报表").head(TRwdTodayReportModel.class).build();
                excelWriter.write(trwdModels, writeSheet1);
                excelWriter.finish();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("导出日报表出错", e);
            }
        }
    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_DISPATCH)
    public Object getAllFjzfs(String fjzfs1) {
        log.info("获取浇筑方式");
        Wrapper<TRwd> wrapper = new EntityWrapper<>();
        wrapper.orderBy("max(Frwdh)", false);
        wrapper.setSqlSelect(" Fjzfs ");
        if (StringUtils.isNotBlank(fjzfs1)) {
            wrapper.like("Fjzfs", fjzfs1);
        }
        wrapper.isNotNull("Fjzfs");
        wrapper.groupBy("Fjzfs");
        List<TRwd> list = this.selectList(wrapper);
        if (list == null || list.isEmpty()) {
            return new ErrorResponseData("卸料方式查询失败");
        }
        String jsonStr = JSON.toJSONString(list);
        JSONArray jsonArray = JSON.parseArray(jsonStr);
        List<String> stringList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            try {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                String fjzfs = jsonObject.getString("fjzfs");
                if (StringUtils.isNotBlank(fjzfs)) {
                    fjzfs = fjzfs.replace("\t", "");
                    fjzfs = fjzfs.replace("\r", "");
                    fjzfs = fjzfs.replace("\n", "");
                    fjzfs = fjzfs.trim();
                    if (StringUtils.isNotBlank(fjzfs)) {
                        stringList.add(fjzfs);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new SuccessResponseData(stringList);
    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_DISPATCH)
    public Object getGddh(String gddh) {
        log.info("获取工地电话：{}", gddh);
        Wrapper<TRwd> wrapper = new EntityWrapper<>();
        wrapper.orderBy("max(Frwdh)", false);
        wrapper.setSqlSelect(" Ftbj ");
        wrapper.like("Ftbj", gddh);
        wrapper.groupBy("Ftbj");
        List<TRwd> list = this.selectList(wrapper);
        if (list == null || list.isEmpty()) {
            return new ErrorResponseData("工地电话查询失败");
        }
        List<String> stringList = new ArrayList<>();
        for (TRwd trwd : list) {
            String ftbj = trwd.getFtbj();
            if (StringUtils.isNotBlank(ftbj)) {
                ftbj = ftbj.replace("\t", "");
                ftbj = ftbj.replace("\r", "");
                ftbj = ftbj.replace("\n", "");
                ftbj = ftbj.trim();
                if (StringUtils.isNotBlank(ftbj)) {
                    ftbj = ftbj.split("\\|")[0];
                    stringList.add(ftbj);
                }
            }
        }
        /*List<String> gddhs = list.stream().map(a -> {
            String ftbj = a.getFtbj();
            return ftbj.split("\\|")[0];
        }).collect(Collectors.toList());*/
        return new SuccessResponseData(stringList);
    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_DISPATCH)
    public Object getFjhrq(String fjhrq) {
        log.info("获取浇筑时间：{}", fjhrq);
        Wrapper<TRwd> wrapper = new EntityWrapper<>();
        wrapper.orderBy("max(Frwdh)", false);
        wrapper.setSqlSelect(" Fjhrq ");
        String spaceStr = " ";
        if (StringUtils.isNotBlank(fjhrq) && fjhrq.split(spaceStr).length >= 1) {
            wrapper.like("Fjhrq", fjhrq.split(" ")[0]);
        }
        wrapper.groupBy("Fjhrq");
        List<TRwd> list = this.selectList(wrapper);
        if (list == null || list.isEmpty()) {
            return new ErrorResponseData("浇筑时间查询失败");
        }
        List<String> stringList = new ArrayList<>();
        int i = 0;
        for (TRwd trwd : list) {
            String fjhrq1 = trwd.getFjhrq();
            if (StringUtils.isNotBlank(fjhrq1)) {
                fjhrq1 = fjhrq1.replace("\t", "");
                fjhrq1 = fjhrq1.replace("\r", "");
                fjhrq1 = fjhrq1.replace("\n", "");
                fjhrq1 = fjhrq1.trim();
                if (StringUtils.isNotBlank(fjhrq1)) {
                    stringList.add(fjhrq1);
                }
            }
            i++;
            if (i > 50) {
                break;
            }
        }
        /*List<String> gddhs = list.stream().map(a -> {
            String ftbj = a.getFtbj();
            return ftbj.split("\\|")[0];
        }).collect(Collectors.toList());*/
        return new SuccessResponseData(stringList);
    }
}
